package com.SFA.Main;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class HttpFactory
{

	public static class HttpFactorys
	{

		private final static String     LoginURL   = "https://ihome.cofco.com/dana-na/auth/url_default/login.cgi";
		public static DefaultHttpClient HttpClient = SSLSocketFactoryEx.getNewHttpClient();
		public static List<Cookie>      cookies;
		public static CookieStore       store      = null;
		public static HttpContext       context    = new BasicHttpContext();
		public static String	    usernmae;
		public static String	    password;

		public static void InItHttpClientSetting()
		{
			HttpClient.getParams()
			.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
					15 * 1000);
			// 设置允许重定向
			HttpClient.getParams()
			.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);

		}

		public static boolean Login(String UserName, String Password)
		{
			boolean result = false;

			try
			{

				InItHttpClientSetting();
				usernmae = UserName;
				password = Password;

				HttpResponse response;
				HttpPost httpost = new HttpPost(LoginURL);
				List<NameValuePair> nvps = new ArrayList<NameValuePair>();
				nvps.add(new BasicNameValuePair("username", UserName));
				nvps.add(new BasicNameValuePair("password", Password));
				nvps.add(new BasicNameValuePair("realm", "cofco_realm"));
				nvps.add(new BasicNameValuePair("btnSubmit.x", "28"));
				nvps.add(new BasicNameValuePair("btnSubmit.y", "17"));
				nvps.add(new BasicNameValuePair("tz_offset", "480"));
				httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

				response = HttpClient.execute(httpost, context);

				HttpEntity entity = response.getEntity();

				String strRet = EntityUtils.toString(entity);

				if (strRet.indexOf("name=\"frmLogin\"") > -1)
				{
					return result;

				}
				// 判断是否为确认界面，如果是确认界面，则重新发送确认请求
				if (strRet.indexOf("name=\"frmConfirmation\"") > -1)
				{
					// 获取
					String Key = "name=\"FormDataStr\"";
					int index = strRet.indexOf(Key);
					int EndIndex = strRet.indexOf(">", index);
					String SubString = strRet.substring(index + Key.length(),
							EndIndex);
					SubString = SubString.replace("value=\"", "");
					SubString = SubString.replace("\"", "");

					nvps.clear();
					nvps.add(new BasicNameValuePair("btnContinue",
					"%E7%BB%A7%E7%BB%AD%E4%BC%9A%E8%AF%9D"));
					nvps.add(new BasicNameValuePair("FormDataStr", SubString));

					HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
					HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
					String currentUrl = (currentReq.getURI().isAbsolute())
					? currentReq.getURI()
							.toString()
							: (currentHost.toURI() + currentReq.getURI());
							nvps.add(new BasicNameValuePair("Referer", currentUrl));

							httpost = new HttpPost(LoginURL);
							httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
							response = HttpClient.execute(httpost, context);
							entity = response.getEntity();

				}

				if (entity != null)
				{
					entity.consumeContent();
				}
				cookies = HttpClient.getCookieStore().getCookies();
				if (response.getStatusLine().getStatusCode() == 200
						&& !cookies.isEmpty())
				{
					store = HttpClient.getCookieStore();

					result = true;
				}
				else
				{
					store = null;
					cookies = null;
				}

			}
			catch (Exception e)
			{
				e.printStackTrace();
				return false;
			}
			return result;
		}

		public static String ReloginByContent(String UserName,
				String Password,
				CookieStore cs)
		{
			DefaultHttpClient client = SSLSocketFactoryEx.getNewHttpClient();

			try
			{
				// InItHttpClientSetting();
				usernmae = UserName;
				password = Password;

				HttpResponse response;
				HttpPost httpost = new HttpPost(LoginURL);
				List<NameValuePair> nvps = new ArrayList<NameValuePair>();
				nvps.add(new BasicNameValuePair("username", UserName));
				nvps.add(new BasicNameValuePair("password", Password));
				nvps.add(new BasicNameValuePair("realm", "cofco_realm"));
				nvps.add(new BasicNameValuePair("btnSubmit.x", "28"));
				nvps.add(new BasicNameValuePair("btnSubmit.y", "17"));
				nvps.add(new BasicNameValuePair("tz_offset", "480"));
				httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

				client.setCookieStore(cs);
				response = client.execute(httpost, context);

				HttpEntity entity = response.getEntity();

				String strRet = EntityUtils.toString(entity, "UTF-8");

				if (strRet.indexOf("name=\"frmLogin\"") > -1)
				{
					return null;

				}
				// 判断是否为确认界面，如果是确认界面，则重新发送确认请求
				if (strRet.indexOf("name=\"frmConfirmation\"") > -1)
				{
					// 获取
					String Key = "name=\"FormDataStr\"";
					int index = strRet.indexOf(Key);
					int EndIndex = strRet.indexOf(">", index);
					String SubString = strRet.substring(index + Key.length(),
							EndIndex);
					SubString = SubString.replace("value=\"", "");
					SubString = SubString.replace("\"", "");

					nvps.clear();
					nvps.add(new BasicNameValuePair("btnContinue",
					"%E7%BB%A7%E7%BB%AD%E4%BC%9A%E8%AF%9D"));
					nvps.add(new BasicNameValuePair("FormDataStr", SubString));

					HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
					HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
					String currentUrl = (currentReq.getURI().isAbsolute())
					? currentReq.getURI()
							.toString()
							: (currentHost.toURI() + currentReq.getURI());
							nvps.add(new BasicNameValuePair("Referer", currentUrl));

							httpost = new HttpPost(LoginURL);
							httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
							response = client.execute(httpost, context);
							entity = response.getEntity();

				}

				/*
				 * if (entity != null) { entity.consumeContent(); }
				 */
				cookies = client.getCookieStore().getCookies();
				if (response.getStatusLine().getStatusCode() == 200
						&& !cookies.isEmpty())
				{
					store = client.getCookieStore();

					return MyUtil.readContents(entity.getContent());
				}
				else
				{
					store = null;
					cookies = null;
				}

			}
			catch (Exception e)
			{
				e.printStackTrace();
				return null;
			}
			finally
			{

				if (client != null)
				{
					client.getConnectionManager().shutdown();
				}

			}
			return null;
		}

		public static String GetHttpContent(String URL) throws ClientProtocolException,
		IOException
		{

			// 以下的内容只需要在每次请求的时候发送调用即可,以下代码为显示RSS源内容
			DefaultHttpClient client = SSLSocketFactoryEx.getNewHttpClient();
			client.setCookieStore(store);
			HttpGet httpget = new HttpGet(URL);

			// HttpClient.setCookieStore(store);
			HttpResponse response = client.execute(httpget, context);

			HttpEntity entity = response.getEntity();

			if (!(response.getStatusLine().getStatusCode() == 200))
				return null;
			HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
			HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
			String currentUrl = (currentReq.getURI().isAbsolute())
			? currentReq.getURI()
					.toString()
					: (currentHost.toURI() + currentReq.getURI());

					if (!URL.equals(currentUrl))
					{
						if (entity != null)
						{
							entity.consumeContent();

						}
						return ReloginByContent(usernmae,
								password,
								HttpClient.getCookieStore());
					}
					String strRet = null;
					try
					{
						strRet = MyUtil.readContents(entity.getContent());

					}
					catch (Exception e)
					{
						e.printStackTrace();
					}

					if (entity != null)
					{
						entity.consumeContent();
					}
					return strRet;
		}

		public static Bitmap GetInputStream(String URL) throws ClientProtocolException,
		IOException
		{

			HttpEntity entity = null;

			DefaultHttpClient client = SSLSocketFactoryEx.getNewHttpClient();
			client.setCookieStore(store);
			// synchronized (HttpClient)
			//
			// {
			// 以下的内容只需要在每次请求的时候发送调用即可,以下代码为显示RSS源内容
			HttpGet httpget = new HttpGet(URL);
			HttpResponse response = client.execute(httpget, context);

			entity = response.getEntity();
			if (!(response.getStatusLine().getStatusCode() == 200))
				return null;
			HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
			HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
			String currentUrl = (currentReq.getURI().isAbsolute())
			? currentReq.getURI()
					.toString()
					: (currentHost.toURI() + currentReq.getURI());
					if (!URL.equals(currentUrl))
					{

					}

					InputStream is = null;
					try
					{
						is = entity.getContent();
						ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
						byte[] buffer = new byte[1024];
						int len = -1;
						while ((len = is.read(buffer)) != -1)
						{
							outSteam.write(buffer, 0, len);
						}
						outSteam.close();

						Bitmap bitmap = BitmapFactory.decodeByteArray(outSteam.toByteArray(),
								0,
								outSteam.size());

						return bitmap;
					}
					catch (IllegalStateException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					catch (IOException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					finally
					{
						if (is != null)
						{
							is.close();
							is = null;
						}
					}
					return null;
		}

		/***
		 * 获取请求的流
		 */
		@SuppressWarnings("unused")
		public static InputStream GetStream(String URL) throws ClientProtocolException,
		IOException
		{

			DefaultHttpClient client = SSLSocketFactoryEx.getNewHttpClient();

			HttpGet httpget = new HttpGet(URL);

			client.setCookieStore(store);
			HttpResponse response = client.execute(httpget, context);

			HttpEntity entity = response.getEntity();

			if (!(response.getStatusLine().getStatusCode() == 200))
				return null;
			HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
			HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
			String currentUrl = (currentReq.getURI().isAbsolute())
			? currentReq.getURI()
					.toString()
					: (currentHost.toURI() + currentReq.getURI());

					// if (!URL.equals(currentUrl))
					// {
					// if (entity != null)
					// {
					// entity.consumeContent();
					//
					// }
					// return ReloginByContent(usernmae,
					// password,
					// HttpClient.getCookieStore());
					// }
					return entity.getContent();
		}

	}

	// }

}
